package com.aishua.aishuawallet.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.aishua.aishuawallet.Constant;
import com.aishua.aishuawallet.R;
import com.aishua.aishuawallet.bean.ResAuthBean;
import com.aishua.aishuawallet.bean.TokenInfo;
import com.aishua.aishuawallet.business.TaskBusiness;
import com.aishua.aishuawallet.diydialog.TransferDialog;
import com.aishua.aishuawallet.diydialog.xLoadingDialog;
import com.aishua.aishuawallet.mina.MianManager;
import com.aishua.aishuawallet.mina.MinaResultLIstener;
import com.aishua.aishuawallet.utils.AndroidUtils;
import com.aishua.aishuawallet.utils.LogUtils;
import com.aishua.aishuawallet.web3jmanager.Web3jManager;

import org.apache.mina.core.session.IoSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.web3j.protocol.Web3jFactory;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.utils.Convert;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by aishua on 2018/7/31.
 */

public class TransferActivity extends AppCompatActivity {

    private static final String TAG = "TransferActivity-";
    private Context mContext;
    private Button btn_next;
    private Toolbar toolbar;
    private TextView toolbar_title;
    private ImageView img_pickertiem;
    private LinearLayout ll_selectgas;
    private LinearLayout ll_diygas;
    private Switch st_senior;
    private EditText et_address;
    private EditText et_amount;
    private String address;
    private String ethcount;
    private SeekBar sk_gaspay;
    private TextView tv_payeth;
    private EditText et_gasprice;
    private EditText et_gas;
    private EditText et_hex;
    private String gasprice;
    private String gaslimit = new String("100");
    private String hexdata;
    private static int TRANS_CREAT_SUCCESS = 1;
    private static int TRANS_CREAT_FAIL = 2;
    private xLoadingDialog loadingDialog;
    private TransferDialog transferDialog;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            loadingDialog.dismiss();
            transferDialog.dismiss();
            switch (msg.what) {
                case 1:

                    Toast.makeText(mContext, "转账成功", Toast.LENGTH_SHORT).show();

                    break;

                case 2:

                    Toast.makeText(mContext, "转账失败", Toast.LENGTH_SHORT).show();
                    break;

            }

        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer);
        initToolbar();
        mContext = this;
        initView();
        initData();
    }

    private void initData() {

        String jsondata = getIntent().getStringExtra("result");
        LogUtils.v(TAG + "jsondata:" + jsondata);
        if (null != jsondata) {
            parseJson(jsondata);
            et_address.setText(address);
            et_amount.setText(ethcount);
        }
    }

    private void parseJson(String jsondata) {

        try {
            JSONObject jsonObject = new JSONObject(jsondata);
            address = jsonObject.getString("address");
            ethcount = jsonObject.getString("ethcount");


        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void initToolbar() {

        toolbar = findViewById(R.id.toolbar);
        toolbar_title = findViewById(R.id.toolbar_title);
        toolbar_title.setText(getResources().getString(R.string.ethTransfer));
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });

    }

    private void initView() {

        st_senior = findViewById(R.id.st_senior);
        ll_selectgas = findViewById(R.id.ll_selectgas);
        ll_diygas = findViewById(R.id.ll_diygas);
        et_address = findViewById(R.id.et_address);
        et_amount = findViewById(R.id.et_amount);
        sk_gaspay = findViewById(R.id.sk_gaspay);
        tv_payeth = findViewById(R.id.tv_payeth);
        et_gasprice = findViewById(R.id.et_gasprice);
        et_gas = findViewById(R.id.et_gas);
        et_hex = findViewById(R.id.et_hex);
        sk_gaspay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                LogUtils.v(TAG + "progress：" + progress);
                BigDecimal num = new BigDecimal((progress+21000) * 0.000000005);
                String str = new DecimalFormat("0.000000000").format(num);
                gaslimit = (progress+21000) + "";
                tv_payeth.setText(str + " ether");

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {


            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        img_pickertiem = findViewById(R.id.img_pickertiem);
        img_pickertiem.setBackground(getDrawable(R.drawable.code));
        img_pickertiem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(TransferActivity.this, ScannerActivity.class);
                startActivityForResult(intent, 1000);
            }
        });
        btn_next = findViewById(R.id.btn_next);
        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ethcount = et_amount.getText().toString().trim();
                address = et_address.getText().toString().trim();
                String address1 = getResources().getString(R.string.address) + address;
                String paywallet = getResources().getString(R.string.paymentwallet) + "11111111";
                String amount = getResources().getString(R.string.amount) + ethcount;
                LogUtils.v(TAG + "address:" + address);
                transferDialog = TransferDialog.newInstance(address1, paywallet, amount);
                transferDialog.show(getFragmentManager(), "transfer");
                transferDialog.setCancelable(false);
                transferDialog.setSureButtonListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        loadingDialog = xLoadingDialog.newInstance(getResources().getString(R.string.trasfer));
                        loadingDialog.setCancelable(false);
                        loadingDialog.show(getFragmentManager(), "transfer");

                        getTransferData();

                    }
                });
            }
        });

        st_senior.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {

                    ll_diygas.setVisibility(View.VISIBLE);
                    ll_selectgas.setVisibility(View.GONE);

                } else {

                    ll_diygas.setVisibility(View.GONE);
                    ll_selectgas.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (resultCode == 1001) {

            String jsondata = data.getStringExtra("result");

            if (null != jsondata) {
                parseJson(jsondata);
                et_address.setText(address);
                et_amount.setText(ethcount);
            }

        }

    }

    public void getTransferData() {

        if (ll_diygas.getVisibility() == View.VISIBLE) {

            gasprice = et_gasprice.getTransitionName().toString().trim();
            gasprice = Convert.toWei(gasprice, Convert.Unit.GWEI).toString();
            gaslimit = et_gas.getText().toString().trim();
            hexdata = et_hex.getText().toString().trim();

        } else {

            gasprice = Convert.toWei("0.00000005", Convert.Unit.ETHER).toBigInteger().toString();
        }

        ethcount = et_amount.getText().toString().trim();
        ethcount = Convert.toWei(ethcount, Convert.Unit.ETHER).toBigInteger().toString();
        final Web3jManager web3jManager = Web3jManager.getIntance();
        String nonce = web3jManager.ethGetTransactionCount("0x3907d69517b58355207e9a371add9dbc1e198a5b");

        LogUtils.v(TAG + "gasprice:" + gasprice + "gaslimit:" + gaslimit + "address:" + address + "ethcounttowei:" + ethcount + "nonce:" + nonce + "hexdata:" + hexdata);


        TaskBusiness.getInstance().Transaction(this, Constant.TOKENID, "0xcb2b98ec804909147aeaf372c47f1edefa9f63be", ethcount, gasprice, gaslimit, nonce, "0x01", new MinaResultLIstener() {
            @Override
            public void messageReceived(IoSession session, Object message) {

                LogUtils.v(TAG + "message:" + message.toString());

                String msg = message.toString();
                LogUtils.v(TAG + "msg:" + msg);
                String time = msg.substring(70, 74);
                LogUtils.v(TAG + "time:" + time);
                String result = msg.substring(74, 76);
                LogUtils.v(TAG + "result:" + result);

                if (result.equals("00")) {

                    MianManager.getManager().shutDown();
                    String hexvalue = msg.substring(76);
//                    String hexvalue = "0xf86d0f85051f4d5c0083419ce094bafcc84cdad822614c228bb27d10faa7749ba0188806f05b59d3b20000801ba0ba5300d494163d4bda1d062a05077b17b5b83f75b94d7285635eac48a7cc0b87a03b27c7982c07351783f78a62aba35aecd4295081059787e843919526ad59116c";
                    LogUtils.v(TAG+"hexvalue:"+hexvalue);

                    String ethSendTransaction = web3jManager.EthSendRawTransaction("0x"+hexvalue);

                    LogUtils.v(TAG+"ethSendTransaction:"+ethSendTransaction);

                    if (null ==ethSendTransaction){

                        mHandler.sendEmptyMessage(TRANS_CREAT_FAIL);

                    }else {

                        Message message1 = Message.obtain();
                        message1.what = TRANS_CREAT_SUCCESS;
                        message1.obj = ethSendTransaction;
                        mHandler.sendMessage(message1);
                    }

                } else {

                    MianManager.getManager().shutDown();
                    mHandler.sendEmptyMessage(TRANS_CREAT_FAIL);
                }


            }

            @Override
            public void exceptionCaught(IoSession session, Throwable cause) {

                LogUtils.v(TAG + "falimsg:" + cause.getMessage());
                MianManager.getManager().shutDown();


            }
        });

    }

}
